package com.cgnpc.scp.todo.service.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.config.MockClient;
import com.cgnpc.scp.config.MockParam;
import com.cgnpc.scp.todo.service.AueTodoService;
import com.cgnpc.scp.todo.util.QueryTaskParams;
import com.cgnpc.scp.todo.util.RestTemplateUtils;
import com.cgnpc.scp.todo.util.TaskTotalParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.cgnpc.cud.core.common.util.AESUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/******************************
 * 用途说明: 统一待办
 * 作者姓名: chenshijie
 * 创建时间: 2020/10/15 23:35
 ******************************/
@Service
public class AueTodoServiceImpl implements AueTodoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AueTodoServiceImpl.class);

    private String devMode;

    @Value("${spring.profiles.usemock}")
    private void setDevMode(String dm) {
        devMode = dm;
    }

    @Value("${aue.url:}")
    private String aueUrl;

    @Value("${aue.key:}")
    private String aueKey;

    @Value("${aue.syscode:}")
    private String aueSysCode;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MockClient mockClient;

    /**********************************
     * 用途说明: 获取应用任务总条数
     * 参数说明 taskTotalParams
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult queryTaskTotalByApps() throws Exception {
        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"msg\": \"操作成功\",\n" +
//                    "    \"code\": \"0\",\n" +
//                    "    \"data\": {\n" +
//                    "        \"614B53E9-8C7B-4ADD-B7DA-48CF8F53745E\": \"3\",\n" +
//                    "        \"563DFA9D-6CCB-4553-869F-71220DF47413\": \"4\",\n" +
//                    "        \"53446519-C713-42DC-B07E-5FF51BB7BD9C\": \"1\",\n" +
//                    "        \"62C71C2F-9009-45CD-8B06-11361DB9EF71\": \"5\"\n" +
//                    "    }\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
            ApiResult invoke = mockClient.invoke("aueTodoServiceImpl", "queryTaskTotalByApps", null, ApiResult.class, null);
            return invoke;
        }
        TaskTotalParams taskTotalParams = new TaskTotalParams();
        taskTotalParams.setCode("queryTaskTotalByApps");
        taskTotalParams.setTasktype(0);
        HttpHeaders headers = createHeader();
//        if (StringUtils.isBlank(taskTotalParams.getAppids())) {
            taskTotalParams.setAppids("614B53E9-8C7B-4ADD-B7DA-48CF8F53745E,563DFA9D-6CCB-4553-869F-71220DF47413," +
                    "53446519-C713-42DC-B07E-5FF51BB7BD9C,62C71C2F-9009-45CD-8B06-11361DB9EF71");
//        }
        HttpEntity<TaskTotalParams> requestEntity = new HttpEntity<>(taskTotalParams, headers);
//        LOGGER.info("queryTaskTotalByApps--taskTotalParams:{}", JacksonUtil.writeValueAsString(taskTotalParams));
//        LOGGER.info("queryTaskTotalByApps--headers:{}", JacksonUtil.writeValueAsString(headers));
//        ResponseEntity<ApiResult> exchange = restTemplate.exchange(aueUrl, HttpMethod.POST, requestEntity, ApiResult.class);
//        ResponseEntity<ApiResult> post = RestTemplateUtils.post(aueUrl, requestEntity, ApiResult.class);

        ResponseEntity<Map> exchange = restTemplate.exchange(aueUrl, HttpMethod.POST, requestEntity, Map.class);
//        LOGGER.info("queryTaskTotalByApps--result:{}", JacksonUtil.writeValueAsString(exchange.getBody()));
        return ApiResult.success(exchange.getBody());
    }

    /**********************************
     * 用途说明: 获取待办
     * 参数说明 queryTaskParams
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult queryTask(Map map) throws Exception {
        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"msg\": \"操作成功\",\n" +
//                    "    \"code\": \"0\",\n" +
//                    "    \"data\": {\n" +
//                    "        \"total\": 4,\n" +
//                    "        \"data\": [{\n" +
//                    "                \"summary\": \"\",\n" +
//                    "                \"approvemode\": 1,\n" +
//                    "                \"tasktype\": 1,\n" +
//                    "                \"flag\": 0,\n" +
//                    "                \"isMobileApprove\": 1,\n" +
//                    "                \"subject\": \"test\",\n" +
//                    "                \"number\": 1,\n" +
//                    "                \"taskstatus\": 0,\n" +
//                    "                \"assigntime\": \"2019-12-18 09:14:36\",\n" +
//                    "                \"viewformurl\": \"http://cgnoa-p/Runtime/Host.aspx?TaskType=4&FormInsID=0BD80208-F887-4FE4-A516-59E5918DB0AA&DeptID=OGID20120621000000005&ActName=020&ProcInstID=1939575&SecretCode= &ActionFullName=020_相关人传阅\",\n" +
//                    "                \"appname\": \"OA\",\n" +
//                    "                \"appid\": \"614B53E9-8C7B-4ADD-B7DA-48CF8F53745E\",\n" +
//                    "                \"duetime\": \"2099-01-01 00:00:00\",\n" +
//                    "                \"approveformurl\": \"http://cgnoa-p/Runtime/Host.aspx?TaskType=2&FormInsID=0BD80208-F887-4FE4-A516-59E5918DB0AA&DeptID=OGID20120621000000005&ActName=020&ProcInstID=1939575&ActionerChsName=&ActionerAccount=&OperationType=2&ProcId=709&ActID=9513&ActInstID=47604930&SecretCode=1&ActionFullName=020_相关人传阅&CCID=47604930\",\n" +
//                    "                \"taskid\": \"568D844F-6291-49EF-85AA-D6920AB11228\",\n" +
//                    "                \"status\": 1\n" +
//                    "            }, {\n" +
//                    "                \"summary\": \"\",\n" +
//                    "                \"approvemode\": 1,\n" +
//                    "                \"tasktype\": 1,\n" +
//                    "                \"flag\": 0,\n" +
//                    "                \"isMobileApprove\": 0,\n" +
//                    "                \"subject\": \"213\",\n" +
//                    "                \"number\": 2,\n" +
//                    "                \"taskstatus\": 0,\n" +
//                    "                \"assigntime\": \"2020-06-29 17:45:48\",\n" +
//                    "                \"viewformurl\": \"http://cgnoa-p/Runtime/Host.aspx?TaskType=4&FormInsID=D4E80880-46BE-41AE-9120-A1D047CFDA27&DeptID=OGID20120621000000005&ActName=040&ProcInstID=1966395&SecretCode=发文密级ぁ1&ActionFullName=040_公司内部传阅\",\n" +
//                    "                \"appname\": \"OA\",\n" +
//                    "                \"appid\": \"614B53E9-8C7B-4ADD-B7DA-48CF8F53745E\",\n" +
//                    "                \"duetime\": \"2099-01-01 00:00:00\",\n" +
//                    "                \"approveformurl\": \"http://cgnoa-p/Runtime/Host.aspx?TaskType=2&FormInsID=D4E80880-46BE-41AE-9120-A1D047CFDA27&DeptID=OGID20120621000000005&ActName=040&ProcInstID=1966395&ActionerChsName=&ActionerAccount=&OperationType=2&ProcId=369&ActID=4991&ActInstID=47649199&SecretCode=1&ActionFullName=040_公司内部传阅&CCID=47649199\",\n" +
//                    "                \"taskid\": \"B58E55D2-2949-4094-B880-34321D51443E\",\n" +
//                    "                \"status\": 1\n" +
//                    "            }, {\n" +
//                    "                \"summary\": \"\",\n" +
//                    "                \"approvemode\": 1,\n" +
//                    "                \"tasktype\": 1,\n" +
//                    "                \"flag\": 0,\n" +
//                    "                \"isMobileApprove\": 0,\n" +
//                    "                \"subject\": \"2\",\n" +
//                    "                \"number\": 3,\n" +
//                    "                \"taskstatus\": 0,\n" +
//                    "                \"assigntime\": \"2020-06-29 17:58:06\",\n" +
//                    "                \"viewformurl\": \"http://cgnoa-p/Runtime/Host.aspx?TaskType=4&FormInsID=E591AD3C-B097-4EFD-8D1F-053C7967E1AD&DeptID=OGID20120621000000005&ActName=040&ProcInstID=1966396&SecretCode=发文密级ぁ1&ActionFullName=040_公司内部传阅\",\n" +
//                    "                \"appname\": \"OA\",\n" +
//                    "                \"appid\": \"614B53E9-8C7B-4ADD-B7DA-48CF8F53745E\",\n" +
//                    "                \"duetime\": \"2099-01-01 00:00:00\",\n" +
//                    "                \"approveformurl\": \"http://cgnoa-p/Runtime/Host.aspx?TaskType=2&FormInsID=E591AD3C-B097-4EFD-8D1F-053C7967E1AD&DeptID=OGID20120621000000005&ActName=040&ProcInstID=1966396&ActionerChsName=&ActionerAccount=&OperationType=2&ProcId=369&ActID=4991&ActInstID=47649200&SecretCode=1&ActionFullName=040_公司内部传阅&CCID=47649200\",\n" +
//                    "                \"taskid\": \"52ADD83E-2713-4FF6-A53D-4D9124A304D8\",\n" +
//                    "                \"status\": 1\n" +
//                    "            }, {\n" +
//                    "                \"summary\": \"\",\n" +
//                    "                \"approvemode\": 0,\n" +
//                    "                \"tasktype\": 1,\n" +
//                    "                \"flag\": 1,\n" +
//                    "                \"isMobileApprove\": 1,\n" +
//                    "                \"subject\": \"[X1000000]DNMC承包商_预算变更审批流程_￥7.10\",\n" +
//                    "                \"number\": 4,\n" +
//                    "                \"taskstatus\": 0,\n" +
//                    "                \"assigntime\": \"2020-07-02 14:51:13\",\n" +
//                    "                \"viewformurl\": \"http://jtv-upmdemo-t:9090//WfRuntimeHost/ProcessHost.aspx?formtype=docReceive&operation=pendingread&procsetid=1032&ProcinstID=622151&CCID=176033&ActName=020_申请部门审核\",\n" +
//                    "                \"appname\": \"UPM-T\",\n" +
//                    "                \"appid\": \"9A608589-9A3D-4C57-A473-14CC0E9EF4B4\",\n" +
//                    "                \"flagMsg\": \"抱歉，此任务提交处理失败，需重试或联系管理员处理。\",\n" +
//                    "                \"duetime\": \"2099-01-01 00:00:00\",\n" +
//                    "                \"approveformurl\": \"http://jtv-upmdemo-t:9090//WfRuntimeHost/ProcessHost.aspx?formtype=docReceive&operation=pendingread&procsetid=1032&ProcinstID=622151&CCID=176033&ActName=020_申请部门审核\",\n" +
//                    "                \"taskid\": \"9C7F3738-1EE3-4B4A-BA89-4DACF58B270D\",\n" +
//                    "                \"status\": 1\n" +
//                    "            }\n" +
//                    "        ]\n" +
//                    "    }\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);

            List list = new ArrayList();
            list.add(map);
            ApiResult invoke = mockClient.invoke("aueTodoServiceImpl", "queryTask", list, ApiResult.class,Map.class);
            return invoke;
        }
        QueryTaskParams queryTaskParams = new QueryTaskParams();
        queryTaskParams.setCode("queryTask");
        queryTaskParams.setTasktype(0);
        if (StringUtils.isBlank((String)map.get("appid"))) {
            queryTaskParams.setAppid("614B53E9-8C7B-4ADD-B7DA-48CF8F53745E,563DFA9D-6CCB-4553-869F-71220DF47413," +
                    "53446519-C713-42DC-B07E-5FF51BB7BD9C,62C71C2F-9009-45CD-8B06-11361DB9EF71");
        }else{
            queryTaskParams.setAppid((String)map.get("appid"));
        }
        if (StringUtils.isBlank((String)map.get("orderSort"))) {
            queryTaskParams.setOrderSort("desc");
        }else{
            queryTaskParams.setOrderSort((String)map.get("orderSort"));
        }
        if (map.get("pageIndex") == null) {
            queryTaskParams.setPageIndex(1);
        }else{
            queryTaskParams.setPageIndex((Integer)map.get("pageIndex"));
        }
        if (map.get("pageSize")==null) {
            queryTaskParams.setPageSize(10);
        }else{
            queryTaskParams.setPageSize((Integer)map.get("pageSize"));
        }
        HttpHeaders headers = createHeader();
        HttpEntity<QueryTaskParams> requestEntity = new HttpEntity<>(queryTaskParams, headers);
//        LOGGER.info("queryTask--taskTotalParams:{}", JacksonUtil.writeValueAsString(queryTaskParams));
//        LOGGER.info("queryTask--headers:{}", JacksonUtil.writeValueAsString(headers));
        ResponseEntity<ApiResult> exchange = restTemplate.exchange(aueUrl, HttpMethod.POST, requestEntity, ApiResult.class);
//        ResponseEntity<ApiResult> post = RestTemplateUtils.post(aueUrl, requestEntity, ApiResult.class);
//        LOGGER.info("queryTask--result:{}", JacksonUtil.writeValueAsString(exchange.getBody()));
        return exchange.getBody();
    }

    private HttpHeaders createHeader() {
        HttpHeaders headers = new HttpHeaders();
//        String value = AESUtils.aesEncode(CurrentUser.getUser() + "&" + System.currentTimeMillis(), aueKey);
//        headers.add("Aue-Sign", value);
        if("local".equals(devMode)) {
            headers.add("Aue-Sign", "P520227");
        } else {
            headers.add("Aue-Sign", CurrentUser.getUser());
        }
        headers.add("Aue-AppCode", "scp");
        //headers.add("Aue-AppCode", aueSysCode);
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return headers;
    }
}
